/* hal_lptmr.c */

#include "hal_lptmr.h"

typedef void (*LPTMR_HAL_Callback_T)(void);
static LPTMR_HAL_Callback_T sLptmrCallbackFunc;


void LPTMR_HAL_Reset(void)
{
    LPTMR0->PSR = 0U;
    LPTMR0->CSR = LPTMR_CSR_TCF_MASK;
    LPTMR0->CMR = 0xFFFF;
    sLptmrCallbackFunc = 0;
}

bool LPTMR_HAL_ConfigPitMode(LPTMR_PitConfig_T *configPtr)
{
    uint32_t tmp32;
    if (!configPtr)
    {
        return false;
    }

    LPTMR0->CSR = LPTMR_CSR_TCF_MASK; /* disable the timer and clear flag. */

    /* configure the clock source for timer. */
    tmp32 = LPTMR_PSR_PCS(configPtr->ClockSource);
    if (eLPTMR_ClockPreDiv_Disabled == configPtr->ClockPreDiv)
    {
        tmp32 |= LPTMR_PSR_PBYP_MASK;
    }
    else
    {
        tmp32 |= LPTMR_PSR_PRESCALE(configPtr->ClockPreDiv);
    }
    LPTMR0->PSR = tmp32;

    return true;
}

bool LPTMR_HAL_IsTimeout(void)
{
    return (LPTMR_CSR_TCF_MASK == (LPTMR0->CSR & LPTMR_CSR_TCF_MASK));
}

void LPTMR_HAL_ClearTimeoutFlag(void)
{
    LPTMR0->CSR |= LPTMR_CSR_TCF_MASK; /* Clear flag. */
}

void LPTMR_HAL_SetIntEnabledOnTimeout(bool enInt)
{
    if (enInt)
    {
        LPTMR0->CSR |= LPTMR_CSR_TIE_MASK;
    }
    else
    {
        LPTMR0->CSR &= ~LPTMR_CSR_TIE_MASK;
    }
}

void LPTMR_HAL_IRQHandlerHook(void)
{
    LPTMR0->CSR |= LPTMR_CSR_TCF_MASK; /* Clear flag. */
    if (sLptmrCallbackFunc != 0)
    {
        (*sLptmrCallbackFunc)();
    }
}

void LPTMR_HAL_InstallCallbackOnTimeout(void (*func)(void))
{
    sLptmrCallbackFunc = func;
}

void LPTMR_HAL_Start(void)
{
    LPTMR0->CSR |= LPTMR_CSR_TEN_MASK;
}

void LPTMR_HAL_Stop(void)
{
    LPTMR0->CSR &= ~LPTMR_CSR_TEN_MASK;
}


void LPTMR_HAL_SetTimeoutValue(uint16_t val)
{
    LPTMR0->CMR = LPTMR_CMR_COMPARE(val);
}


/* EOF. */

